package com.light.gamecomponents;

import javax.microedition.khronos.opengles.GL10;

import org.anddev.andengine.entity.scene.Scene;
import org.anddev.andengine.entity.sprite.Sprite;
import org.anddev.andengine.extension.physics.box2d.PhysicsWorld;
import org.anddev.andengine.input.touch.TouchEvent;
import org.anddev.andengine.opengl.texture.region.TextureRegion;
import org.anddev.andengine.ui.activity.BaseGameActivity;

import com.badlogic.gdx.math.Vector2;
import com.light.roller.ResourceManager;

public class FormButton implements IGameComponents{

	protected Sprite m_sprite;
	protected String m_textureString;
	protected TextureRegion m_textureRegion;
	protected BaseGameActivity m_game;
	protected Vector2 m_position;
	
	public FormButton(String textureName, BaseGameActivity game, Vector2 position)
	{
		m_game = game;
		m_textureString = textureName;
		m_position = position;
	}
	
	@Override
	public void onLoadEngine() {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void onLoadResources() {
		ResourceManager.onLoadResources(m_textureString, m_game);
		m_textureRegion = ResourceManager.getTextureRegion(m_textureString);
	}

	@Override
	public void unLoadResources() {
		this.m_textureRegion = null;
		ResourceManager.unLoadResources(m_textureString, m_game);
	}

	@Override
	public void onLoadScene(Scene scene, PhysicsWorld physicsWrold) {
		int centerX = (int)(m_position.x - this.m_textureRegion.getWidth() / 2);
        int centerY =  (int)(m_position.y - this.m_textureRegion.getHeight() / 2);
        m_position.x = centerX;
        m_position.y = centerY;
		m_sprite = new Sprite(centerX, centerY, this.m_textureRegion)
		{
			@Override
        	public boolean onAreaTouched(TouchEvent pSceneTouchEvent, float pTouchAreaLocalX, float pTouchAreaLocalY)
        	{
				if (m_sprite.getAlpha() >= 0.5f && pSceneTouchEvent.isActionDown())
					whenClicked();
				return true;
        	}
		};
		m_sprite.setBlendFunction(GL10.GL_SRC_ALPHA, GL10.GL_ONE_MINUS_SRC_ALPHA);
		scene.registerTouchArea(m_sprite);
		scene.attachChild(m_sprite);
		
	}

	@Override
	public void removeFromScene(Scene scene, PhysicsWorld physicsWorld) {
		scene.detachChild(m_sprite);
		scene.unregisterTouchArea(m_sprite);
		m_sprite = null;
		
	}
	
	public void setPosition(Vector2 position)
	{
		m_position = position;
		m_sprite.setPosition(position.x, position.y);
	}
	
	public void whenClicked() {}
	
	public void show() { m_sprite.setAlpha(1.0f); }
	public void hide() { m_sprite.setAlpha(0.0f); }
	public void rotate(float angle) { m_sprite.setRotation(angle); }
	public void setRotationCenter(Vector2 center) { m_sprite.setRotationCenter(center.x, center.y);}


	
}
